<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/custom.form.css">
    <style type="text/css">
        .layui-table-cell {
            font-size:14px;
            padding:0 5px;
            height:auto;
            overflow:visible;
            text-overflow:inherit;
            white-space:normal;
            word-break: break-all;
        }
    </style>
</head>
<body>


<div class="table_div">
    <div id="searchParam"  shiro:hasPermission="dlExamResult:list">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" id="key" class="layui-input"  autocomplete="off" placeholder="请输入">
            </div>

            <div class="layui-input-inline ">
                <button class="layui-btn" onclick="search()"  id="search">查询</button>
                <button class="layui-btn"   id="export">导出全部</button>
            </div>
        </div>

    </div>
    <table class="layui-table" id="showTable" lay-filter="showTable" ></table>
</div>

<div hidden id="courseBtnList">
    <div id="btnsId" style="margin-top: 40px; text-align: center;"></div>
</div>

<div hidden id="studentDiv">
    <div class="panel-heading title"></div>
    <div class="layui-card-body">
        <table class="layui-table" id="studentTab" lay-filter="studentTable" ></table>
    </div>
</div>

<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="input" shiro:hasPermission="dlExamResult:update">成绩录入</a>
</script>

</body>
</html>
<script src="/layui/layui.all.js"></script>
<script src="/js/core.util.js"></script>
<script>


    //获取token
    var token = CoreUtil.getData("access_token");
    //地址栏转义token中的#号
    var tokenQuery = token.replace("#", "%23");
    var tableIns1;
    var studentTableIns;
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = jQuery = layui.jquery;
    var laydate = layui.laydate;


    var gradeDatas = "[[${@dlGradeService.getGrades()}]]".replace(/&quot;/g,"\"");


    layui.use(['table', 'layer', 'laydate'], function () {

        //加载table
        tableIns1 = table.render({
            elem: '#showTable'
            , contentType: 'application/json'
            , headers: {"authorization": token}
            , page: true //开启分页
            , url: '/dlExamPlan/inputList' //数据接口
            , method: 'POST'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                    "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                }
            }
            , cols: [
                [
                    {field: 'id', title: '', sort: true, hide: true},
                    {field: 'name', title: '考试标题', sort: true},
                    {field: 'gradeId', title: '年级', sort: true, templet: function (item) {
                            return CoreUtil.getBeanLabel(gradeDatas, item.gradeId, "id", "gradeNameLabel");
                        }},
                    {width: 120, toolbar: "#tool", title: '操作'}
                ]
            ]
        });


        studentTableIns = table.render({
            elem: '#studentTab'
            , contentType: 'application/json'
            , headers: {"authorization": token}
            , page: true //开启分页
            , limit: 50
            , method: 'POST'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                    "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                }
            }
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', sort: true, hide: true},
                    {field: 'studentName', title: '学生姓名', sort: true},
                    {field: 'examRoomName', title: '考场', sort: true},
                    {field: 'totalScore', title: '总分', sort: true},
                    {field: 'seatNum', title: '座位号', sort: true},
                    {field: 'score', title: '得分', sort: true, edit: 'text'},
                    {field: 'remark', title: '备注', sort: true, edit: 'text'}
                ]
            ]
        });

        // table.on('rowDouble(showTable)', function (obj) {
        //     var data = obj.data;
        //     loadStudentScoreTab(data.id);
        //     openWin(data.examTitle + " -- " + data.courseName);
        // });


        table.on('edit(studentTable)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            console.log(obj.value); //得到修改后的值
            console.log(obj.field); //当前编辑的字段名
            console.log(obj.data); //所在行的所有相关数据
            var params = {};
            params[obj.field] = obj.value;
            if(obj.field == "score" && !CoreUtil.isEmpty(obj.value)){
                //检查
                if(!CoreUtil.isRealNum(obj.value)){
                    layer.msg("非法输入，请输入数字");
                    var text = $(this).prev().text();//得到修改前的值
                    $(this).val(text);
                    return;
                }

                if(obj.value < 0){
                    layer.msg("分数只能是正数");
                    var text = $(this).prev().text();//得到修改前的值
                    $(this).val(text);
                    return;
                }
                if(obj.value > obj.data.totalScore){
                    layer.msg("分数不能超过总分");
                    var text = $(this).prev().text();//得到修改前的值
                    $(this).val(text);
                    return;
                }
            }


            params.id = obj.data.id;

            CoreUtil.sendPut("/dlExamScore/update",params, function (res) {
                layer.msg("保存成功");
            });
        });


        //列操作
        table.on('tool(showTable)',function (obj) {
            var data = obj.data;
            if(obj.event == "input"){
                openCourseListBtn(data);
            }
        });

    });
    // loadStudentScoreTab(data.id);
    // openWin(data.examTitle + " -- " + data.courseName);

    function openCourseListBtn(colData) {
        var examId = colData.id;

        var data = null;
        CoreUtil.sendPost("/dlExamSubject/listByPage", {examId: examId}, function (res) {
            data = res.data.records;
        }, false);

        var btns = $("#btnsId");
        btns.empty();
        var html = "";
        for(var i = 0; i < data.length; i++){
            html += '<a class="layui-btn layui-btn-radius layui-btn-primary" onclick="inputScore(\'' + examId + '\', \'' + data[i].courseId + '\', \''+ colData.name + '--' + data[i].courseName +'\')">'+ data[i].courseName +'</a>';
        }
        btns.append(html);
        layer.open({
            type: 1,
            content: $("#courseBtnList"),
            title: "成绩录入--选择科目",
            area: ['400px', '300px'],
            btn: ["关闭"],
            yes: function (index) {
                layer.close(index);
            }
        });
    }


    function inputScore(examId, courseId, title){
        loadStudentScoreTab(examId, courseId);
        openWin(title);
    }



    function openWin(title) {

        var index = layer.open({
            type: 1,
            content: $('#studentDiv'),
            area: ['1000px', '600px'],
            title: title + "  成绩录入",
            maxmin: true,
            btn: ["保存"],
            yes: function (index, layero) {
                layer.close(index);
            }
        });
        layer.full(index);
    }


    function loadStudentScoreTab(examId, courseId) {
        studentTableIns.reload({
            url: '/dlExamScore/listByPage', //数据接口
            where: {
                courseId: courseId,
                examId: examId
            }
        });
    }

    //执行查询
    function search() {
        //这里以搜索为例
        tableIns1.reload({
            where: { //设定异步数据接口的额外参数，任意设
                key: $("#key").val()
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    };

    $(document).on('keydown', '.layui-input',
        function(event) {
            var td = $(this).parent('td');
            var index = td.index();
            var tr = td.parent('tr');
            switch (event.key) {
                case "ArrowUp"://上键
                    tr['prev']().children('td').eq(index).click();
                    break;
                case "ArrowDown"://下键
                    tr['next']().children('td').eq(index).click();
                    break;
                case "ArrowLeft"://左键
                    td['prevAll']('[data-edit="text"]:first').click();
                    break;
                case "ArrowRight"://右键
                    td['nextAll']('[data-edit="text"]:first').click();
                    break;
            }
        }
    );
</script>